const fs = require('fs');

function parse16(hex) {
  hex= parseInt(hex, 16); 
  hex= hex| 0xFFFFFFFF00000000; 
  return hex;
}

export function readDatFile(path) {
  return new Promise((resolve, reject) => {
    const resData = {};
    fs.readFile(path, function (err, data) {
      if (err) {
        console.log(err);        
        reject(err);
      } else {
          const dataChest = [];
          const dataHead = [];
          let timeStamp = 0;
          for (let i = 0, len = data.length; i < len; i++) {
            if ((i > 4) && (data[i] === 239) && (data[i - 1] === 205) && (data[i - 2] === 171) && (data[i - 3] === 137)) {
              const itemObj = {};
              // const time1 = data[i - 4];
              // const time2 = data[i - 5];
              // const time3 = data[i - 6];
              // const time4 = data[i - 7];
              let nextIndex;
              if (!timeStamp) {
                // timeStamp = parseInt(((time1 < 16 ? ('0' + time1.toString(16)) : time1.toString(16)) + (time2 < 16 ? ('0' + time2.toString(16)) : time2.toString(16)) + (time3 < 16 ? ('0' + time3.toString(16)) : time3.toString(16)) + (time4 < 16 ? ('0' + time4.toString(16)) : time4.toString(16))), 16);
                timeStamp = 1;
              } else {
                timeStamp = timeStamp + 1;
              }
              for (let k = 1, len2 = 201; k < len2; k++) {
                if ((k % 2 === 0) && (k < 101)) {
                  const num1 = data[i + 200 + k];
                  const num2 = data[i + 200 + k - 1];
                  let str16 = parseInt(((num1 < 16 ? ('0' + num1.toString(16)) : num1.toString(16)) + (num2 < 16 ? ('0' + num2.toString(16)) : num2.toString(16))), 16);
                  if (str16 > 2500) {
                    str16 = parse16('FFFF' + ((num1 < 16 ? ('0' + num1.toString(16)) : num1.toString(16)) + (num2 < 16 ? ('0' + num2.toString(16)) : num2.toString(16))));
                  }
                  dataHead.push([timeStamp * 1000 + 20 * (k / 2 - 1), str16]);
                } else if ((k % 2 === 0) && (k > 101)) {
                  const num1 = data[i + 200 + k];
                  const num2 = data[i + 200 + k - 1];
                  let str16 = parseInt(((num1 < 16 ? ('0' + num1.toString(16)) : num1.toString(16)) + (num2 < 16 ? ('0' + num2.toString(16)) : num2.toString(16))), 16);
                  if (str16 > 2500) {
                    str16 = parse16('FFFF' + ((num1 < 16 ? ('0' + num1.toString(16)) : num1.toString(16)) + (num2 < 16 ? ('0' + num2.toString(16)) : num2.toString(16))));
                  }
                  dataChest.push([timeStamp * 1000 + 20 * (k / 2 - 1 - 50), str16]);
                }
                nextIndex = i + 200 + k;
              }
              itemObj.timeStamp = timeStamp;
              i = nextIndex + 1;
            }
          }
          resData.chest = dataChest;
          resData.head = dataHead;
          resolve(resData);
      }
    });
  })
}

export function changeJsonFileTags(path, tagsArr) {
  fs.exists(path, function(exists) {
    if (exists) {
      fs.readFile(path, 'utf8', function (errors, data) {
        if (errors || !data) {
          console.log(errors);
        } else {
          const oldTags = JSON.parse(data);
          oldTags.tags = tagsArr;
          // console.log(oldTags, tagsArr);
          fs.writeFile(path, JSON.stringify(oldTags), function (err) {
            if (err) {
              console.log(err);
            } else {
              console.log('insert success');
            }
          });
        }
      });
    } else {
      fs.writeFile(path, `{"tags": [], "event": {}}`, function(err) {
        if(err) {
          console.log('创建文件路径：', path, '失败');
        }
      })
    }
  })
}

export function changeJsonFileMarkArr(path, markArr) {
  fs.exists(path, function(exists) {
    if (exists) {
      fs.readFile(path, 'utf8', function (errors, data) {
        if (errors || !data) {
          console.log(errors);
        } else {
          const jsonData = JSON.parse(data);
          const insertObj = {
            "offbed": [],
            "apnea": [],
          };
          markArr.forEach(element => {
            if (element.eventName === "呼吸暂停") {
              let newObj = {};
              newObj.timeStart = element.timeStart;
              newObj.timeEnd = element.timeEnd;
              insertObj.apnea.push(newObj);
            } else if (element.eventName === "离床") {
              let newObj = {};
              newObj.timeStart = element.timeStart;
              newObj.timeEnd = element.timeEnd;
              insertObj.offbed.push(newObj);
            }
          });
          jsonData.event = insertObj;
          fs.writeFile(path, JSON.stringify(jsonData), function (err) {
            if (err) {
              console.log(err);
            } else {
              console.log('insert success');
            }
          });
        }
      });
    } else {
      fs.writeFile(path, `{"tags": [], "event": ${JSON.stringify(markArr)}}`, function(err) {
        if(err) {
          console.log('创建文件路径：', path, '失败');
        }
      })
    }
  })
}
export function editJsonFileMarkArr(path, markItem, markArr) {
  fs.exists(path, function(exists) {
    if (exists) {
      fs.readFile(path, 'utf8', function (errors, data) {
        if (errors || !data) {
          console.log(errors);
        } else {
          const jsonData = JSON.parse(data);
          const insertObj = {
            "offbed": [],
            "apnea": [],
          };
          markArr.forEach(element => {
            if (element.eventName === "呼吸暂停") {
              let newObj = {};
              newObj.timeStart = element.timeStart;
              newObj.timeEnd = element.timeEnd;
              insertObj.apnea.push(newObj);
            } else if (element.eventName === "离床") {
              let newObj = {};
              newObj.timeStart = element.timeStart;
              newObj.timeEnd = element.timeEnd;
              insertObj.offbed.push(newObj);
            }
          });
          jsonData.event = insertObj;
          fs.writeFile(path, JSON.stringify(jsonData), function (err) {
            if (err) {
              console.log(err);
            } else {
              console.log('insert success');
            }
          });
        }
      });
    } else {
      fs.writeFile(path, `{"tags": [], "event": {}}`, function(err) {
        if(err) {
          console.log('创建文件路径：', path, '失败');
        }
      })
    }
  })
}
